package com.ma.cloud.config;

import com.netease.nim.camellia.hot.key.extensions.discovery.eureka.EurekaHotKeyServerDiscovery;
import com.netease.nim.camellia.hot.key.sdk.CamelliaHotKeyCacheSdk;
import com.netease.nim.camellia.hot.key.sdk.CamelliaHotKeyMonitorSdk;
import com.netease.nim.camellia.hot.key.sdk.CamelliaHotKeySdk;
import com.netease.nim.camellia.hot.key.sdk.conf.CamelliaHotKeyCacheSdkConfig;
import com.netease.nim.camellia.hot.key.sdk.conf.CamelliaHotKeyMonitorSdkConfig;
import com.netease.nim.camellia.hot.key.sdk.conf.CamelliaHotKeySdkConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * Camellia热key配置
 * @author mr
 * @since 2025-06-23
 */
@Component
@RequiredArgsConstructor
public class CamelliaHotKeyConfig {

    /**
     * 使用注册中心
     */
    private final DiscoveryClient discoveryClient;

    /**
     * 应用名称
     */
    private static final String applicationName = "redis-camellia-hot-key-server";

    /**
     * 刷新间隔，单位秒
     */
    private static final int refreshIntervalSeconds = 5;

    /**
     * 获取CamelliaHotKeyMonitorSdk（仅用于监控热key）
     *
     * @return CamelliaHotKeyMonitorSdk
     */
    @Bean
    public CamelliaHotKeyMonitorSdk getCamelliaHotKeyMonitorSdk() {

        //设置相关参数，一般来说默认即可
        CamelliaHotKeyMonitorSdkConfig monitorSdkConfig = new CamelliaHotKeyMonitorSdkConfig();
        //初始化CamelliaHotKeyMonitorSdk，一般全局一个即可
        return new CamelliaHotKeyMonitorSdk(getCamelliaHotKeySdk(), monitorSdkConfig);
    }

    /**
     * 获取CamelliaHotKeyCacheSdk（用于监控热key，并且提供本地缓存功能）
     *
     * @return CamelliaHotKeyCacheSdk
     */
    @Bean
    public CamelliaHotKeyCacheSdk getCamelliaHotKeyCacheSdk() {

        //设置相关参数，一般来说默认即可
        CamelliaHotKeyCacheSdkConfig cacheSdkConfig = new CamelliaHotKeyCacheSdkConfig();
        //初始化CamelliaHotKeyMonitorSdk，一般全局一个即可
        return new CamelliaHotKeyCacheSdk(getCamelliaHotKeySdk(), cacheSdkConfig);
    }


    /**
     * 获取CamelliaHotKeySdk
     *
     * @return CamelliaHotKeySdk
     */
    private CamelliaHotKeySdk getCamelliaHotKeySdk() {
        EurekaHotKeyServerDiscovery discovery = new EurekaHotKeyServerDiscovery(discoveryClient, applicationName, refreshIntervalSeconds);
        // 不使用注册中心
//        List<HotKeyServerAddr> list = new ArrayList<>();
//        list.add(new HotKeyServerAddr("127.0.0.1", 7070));
//        LocalConfHotKeyServerDiscovery discovery = new LocalConfHotKeyServerDiscovery(applicationName, list);

        CamelliaHotKeySdkConfig config = new CamelliaHotKeySdkConfig();

        config.setDiscovery(discovery);
        return new CamelliaHotKeySdk(config);
    }
}
